package cn.wildfire.chat.app.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.lqr.imagepicker.ImagePicker;
import com.lqr.imagepicker.bean.ImageItem;
import com.sourcemuch.im.caiba.CaiBaChatApp;
import com.sourcemuch.im.caiba.ManumotiveIBinder;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import cn.wildfire.chat.app.extendsion.ui.ToastTip;
import cn.wildfire.chat.app.extendsion.widgets.CircleImageView;
import cn.wildfire.chat.kit.WfcBaseActivity;
import cn.wildfire.chat.kit.common.OperateResult;
import cn.wildfire.chat.kit.contact.model.UIUserInfo;
import cn.wildfire.chat.kit.conversation.ConversationActivity;
import cn.wildfire.chat.kit.conversationlist.ConversationGroupListViewModel;
import cn.wildfire.chat.kit.group.GroupViewModel;
import cn.wildfire.chat.kit.third.utils.ImageUtils;
import cn.wildfire.chat.kit.user.UserViewModel;
import cn.wildfirechat.message.MessageContentMediaType;
import cn.wildfirechat.model.Conversation;
import cn.wildfirechat.model.GroupInfo;
import cn.wildfirechat.model.ModifyGroupInfoType;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.remote.ChatManager;
import cn.wildfirechat.remote.GeneralCallback2;

/**
 * Create by HEKE, 2019/9/10 0:59
 * TODO 创建群聊详细设置界面
 */
public class CreateGroupNextDetaileSetActivity extends WfcBaseActivity {

    public static final int TYPE_CREATE_GROUP = 0x00;
    public static final int TYPE_MODIFY_GROUP = 0x01;

    @BindView(R2.id.groupIcon)
    CircleImageView groupIcon;
    @BindView(R2.id.photoLayout)
    RelativeLayout photoLayout;
    @BindView(R2.id.groupNameEditText)
    EditText groupNameEditText;

    protected int type = TYPE_CREATE_GROUP;
    protected GroupInfo groupInfo;

    /**
     * 创建群组对象数据
     */
    private ArrayList<UIUserInfo> userInfos;
    protected GroupViewModel groupViewModel;
    protected UserViewModel userViewModel;
    protected ConversationGroupListViewModel conversationGroupListViewModel;

    protected byte[] portraitContent;

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_create_group_detaile_set;
    }

    @Override
    protected void afterViews() {
        super.afterViews();
        try {
            type = getIntent().getIntExtra("choosetype", TYPE_CREATE_GROUP);
            groupInfo = getIntent().getParcelableExtra("groupInfo");
            groupViewModel = ViewModelProviders.of(this).get(GroupViewModel.class);
            userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
            conversationGroupListViewModel = (ConversationGroupListViewModel) manumotiveIBinder.getObject(ManumotiveIBinder.GROUP_LIST_VIEWMODEL);
            UserInfo userInfo = userViewModel.getUserInfo(userViewModel.getUserId(), true);
            if (type == TYPE_CREATE_GROUP) {
                userInfos = getIntent().getParcelableArrayListExtra("uiUserInfoArrayList");
                userInfos.add(UIUserInfo.userInfoToUIUserInfo(userInfo));
                portraitContent = getDefaultPotriaitContent();
            } else if (type == TYPE_MODIFY_GROUP) {
                groupNameEditText.setText("" + groupInfo.name);
                portraitContent = null;
                Glide.with(this).asBitmap().load(groupInfo.portrait).into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        groupIcon.setImageBitmap(resource);
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (groupNameEditText != null) {
            groupNameEditText.setFocusable(true);
            groupNameEditText.setFocusableInTouchMode(true);
            groupNameEditText.setCursorVisible(true);
            groupNameEditText.requestFocus();
            groupNameEditText.requestLayout();
            CaiBaChatApp.getMainHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    showInputMethod();
                }
            }, 200);
        }
    }

    private byte[] getDefaultPotriaitContent() {
        byte[] portraitContent = null;
        try {
            @SuppressLint("ResourceType") InputStream inputStream = getResources().openRawResource(R.mipmap.button_group);
            portraitContent = new byte[inputStream.available()];
            inputStream.read(portraitContent);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return portraitContent;
    }

    @Override
    protected void setTitleCenterThenSetSearchView() {
        super.setTitleCenterThenSetSearchView();
        setToolbarOrReplaceType(true, 3);
        boolean createGroup = type == TYPE_CREATE_GROUP;
        setReplaceTitle(null, createGroup ? R.string.create_group_title : R.string.change_group_info_set);
        setSearchLayoutVisibility(false);
        getRightTxtView().setBackgroundResource(R.drawable.commom_green_radiusmuch);
        getRightTxtView().setTextColor(getResources().getColor(R.color.white));
        setTextThenBinClickForRightTextView(View.VISIBLE, getString(R.string.done_title), new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                createGroup();
            }
        });
    }

    private static final int REQUEST_CODE_PICK_IMAGE = 10000;

    @OnClick(R2.id.photoLayout)
    public void onViewClicked() {
        // 请求更换头像
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
            if (!checkPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE})) {
                return;
            }
        }
        ImagePicker.picker().pick(this, REQUEST_CODE_PICK_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        try {
            if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                String imagePath = ImageUtils.genThumbImgFile(images.get(0).path).getAbsolutePath();
                FileInputStream fis = new FileInputStream(imagePath);
                portraitContent = new byte[fis.available()];
                fis.read(portraitContent);
                fis.close();
                groupIcon.setImageBitmap(BitmapFactory.decodeByteArray(portraitContent, 0, portraitContent.length));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 输入法弹出与隐藏
     */
    private void showInputMethod() {
        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 创建群组名称
     *
     * @param customGroupName
     * @return
     */
    public String createGroupName(String customGroupName) {
        String groupName = "";
        try {
            if (!cn.wildfire.chat.app.extendsion.utils.TextUtils.isTextEmpty(customGroupName)) {
                groupName = customGroupName;
            } else {
                if (userInfos != null && userInfos.size() > 3) {
                    for (int i = 0; i < 3; i++) {
                        UserInfo friend = userInfos.get(i).getUserInfo();
                        groupName += friend.displayName + "、";
                    }
                } else {
                    for (UIUserInfo friend : userInfos) {
                        groupName += friend.getUserInfo().displayName + "、";
                    }
                }
                groupName = groupName.substring(0, groupName.length() - 1);
                if (groupName.length() >= 28) {
                    groupName = userInfos.get(0).getUserInfo().displayName + "等";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return groupName;
    }


    protected boolean createGroupLock;
    protected MaterialDialog dialog;

    /**
     * 获取群组所有成员编号列表
     *
     * @param addSelf
     */
    private ArrayList<String> getGroupIds(boolean addSelf) {
        if (userInfos == null) {
            return null;
        }
        ArrayList<String> selectedIds = new ArrayList<>();
        for (UIUserInfo userInfo : userInfos) {
            selectedIds.add(userInfo.getUserInfo().uid);
        }
        if (addSelf) {
            selectedIds.add(ChatManager.Instance().getUserId());
        }
        return selectedIds;
    }

    /**
     * TODO 创建群聊
     */
    private void createGroup() {
        try {
            if (type == TYPE_MODIFY_GROUP) {
                // 修改群名称、头像
                String newGroupName = groupNameEditText.getText().toString();
                if (!cn.wildfire.chat.app.extendsion.utils.TextUtils.isTextEmpty(newGroupName) && !newGroupName.equals(groupInfo.name)) {
                    groupViewModel.modifyGroupInfo(groupInfo.target, ModifyGroupInfoType.Modify_Group_Name, newGroupName, null)
                            .observe(this, new Observer<OperateResult<Boolean>>() {
                                @Override
                                public void onChanged(@Nullable OperateResult operateResult) {
                                    if (operateResult.isSuccess()) {
                                        finish();
                                    } else {
                                        Toast.makeText(CreateGroupNextDetaileSetActivity.this, "修改群名称失败: " + operateResult.getErrorCode(), Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                }
                // 刷新头像
                if (portraitContent != null) {
                    ChatManager.Instance().uploadMedia(portraitContent, MessageContentMediaType.PORTRAIT.getValue(), new GeneralCallback2() {
                        @Override
                        public void onSuccess(String result) {
                            groupViewModel.modifyGroupInfo(groupInfo.target, ModifyGroupInfoType.Modify_Group_Portrait, result, null).observe(CreateGroupNextDetaileSetActivity.this
                                    , new Observer<OperateResult<Boolean>>() {
                                        @Override
                                        public void onChanged(@Nullable OperateResult operateResult) {
                                            if (operateResult.isSuccess()) {
                                                finish();
                                            } else {
                                                Toast.makeText(CreateGroupNextDetaileSetActivity.this, "修改群头像失败: " + operateResult.getErrorCode(), Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });
                        }

                        @Override
                        public void onFail(int errorCode) {
                            ToastTip.tip("修改群头像失败:" + errorCode);
                        }
                    });
                }
            } else {
                if (!createGroupLock) {
                    createGroupLock = true;
                    dialog = new MaterialDialog.Builder(this)
                            .content("创建中...")
                            .progress(true, 100)
                            .cancelable(false)
                            .build();
                    dialog.show();
                    String groupNameSet = groupNameEditText.getText().toString();
                    String groupName = createGroupName(groupNameSet);
                    if (portraitContent == null) {
                        portraitContent = getDefaultPotriaitContent();
                    }

                    groupViewModel.createGroup(CreateGroupNextDetaileSetActivity.this,
                            getGroupIds(false), groupName, portraitContent).observe(CreateGroupNextDetaileSetActivity.this,
                            new Observer<OperateResult<String>>() {
                                @Override
                                public void onChanged(OperateResult<String> stringOperateResult) {
                                    ToastTip.tip("创建成功!");
                                    try {
                                        Intent intent = ConversationActivity.buildConversationIntent(CreateGroupNextDetaileSetActivity.this, Conversation.ConversationType.Group, stringOperateResult.getResult(), 0);
                                        startActivity(intent);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    } finally {
                                        dialog.dismiss();
                                        finish();
                                    }
                                }
                            });

                }
            }
        } catch (
                Exception e) {
            e.printStackTrace();
        }
    }

}

